package com.sixbro.oauth2.security.service;

import com.sixbro.oauth2.domain.Authority;
import com.sixbro.oauth2.domain.Member;
import com.sixbro.oauth2.security.provider.mobile.MobileUserDetailsService;
import com.sixbro.oauth2.security.domain.OAuth2UserDetails;
import com.sixbro.oauth2.service.MemberService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Mr.Lu
 * @Since: 2020/6/14 22:54
 */
@Log4j2
public class UserDetailsServiceImpl implements UserDetailsService, MobileUserDetailsService {

    @Lazy
    @Autowired
    private MemberService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("密码模式查询用户信息");
        Member sysUser = userService.selectByUsername(username);
        UsernamePasswordAuthenticationFilter filter;
        if (sysUser == null) {
            throw new UsernameNotFoundException("not found user:" + username);
        }
        OAuth2UserDetails userDetail = new OAuth2UserDetails();
        BeanUtils.copyProperties(sysUser,userDetail);
        //这里权限列表,这个为方便直接下（实际开发中查询用户时连表查询出权限）
        Set<Authority> authoritySet = new HashSet<>();
        authoritySet.add(new Authority("admin","管理员权限"));
        userDetail.setAuthorities(authoritySet);
        return userDetail;
    }

    /**
     * 这里模拟根据手机号查询用户
     * @param mobile
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        log.info("手机号模式查询用户信息");
        Member sysUser = userService.selectByMobile(mobile);
        if (sysUser == null) {
            throw new UsernameNotFoundException("not found mobile user:" + mobile);
        }
        OAuth2UserDetails userDetail = new OAuth2UserDetails();
        BeanUtils.copyProperties(sysUser,userDetail);
        userDetail.setAuthorities(new ArrayList<>());
        return userDetail;
    }
}
